package cn.tang.tframe.sdm.utils;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;



public class SpringEl {

	private static SpelParserConfiguration config = new SpelParserConfiguration(true,true);
	private static ExpressionParser parser = new SpelExpressionParser(config);

	public static <E> E eval(Map<String,Object> vars,String el,Class<E> clazz){
		StandardEvaluationContext context = new StandardEvaluationContext();
		if(null != vars){
			context.setVariables(vars);
		}
		Expression expression = parser.parseExpression(el);
		return expression.getValue(context,clazz);
	}
	public static Set eval(Map<String,Object> vars,String el){
		StandardEvaluationContext context = new StandardEvaluationContext();
		if(null != vars){
			context.setVariables(vars);
		}
		Expression expression = parser.parseExpression(el);
		Object value = expression.getValue(context);
		Set objects = new HashSet<>();
		if(value instanceof Collection){
			objects.addAll((Collection)value);
		}else{
			objects.add(value.toString());
		}
		return objects;
	}

}